package com.neshai.webapp.controller;

import com.google.gson.Gson;
import com.neshai.webapp.service.BlockChainInfoService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.*;
import org.web3j.protocol.http.HttpService;

import java.util.Optional;
import java.math.BigInteger;


@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class BlockChainInfoController {
    //quick node openai.net.io@gmail.com
    final private Web3j web3j = Web3j.build(new HttpService("https://rough-ancient-crater.quiknode.pro/bd44bb2c0447e32754f9befc54729bd8c4c74429"));

    private final BlockChainInfoService blockChainInfoService;

    /**
     * @param txHash 交易哈希值
     * @return String
     * @description 根据交易哈希值获取交易信息
     * @author newonexd
     * @date 2022/6/22 21:13
     */
    @GetMapping("/getTransactionInfoByHash")
    public String doGetTransactionInfoByHash(@RequestParam(value = "txHash") String txHash) throws Exception {
        // 获取当前最新区块号
        EthBlockNumber latestBlock = web3j.ethBlockNumber().sendAsync().get();
        BigInteger latestBlockNumber = latestBlock.getBlockNumber();
        System.out.println(latestBlockNumber);

        EthTransaction transaction = web3j.ethGetTransactionByHash(txHash).sendAsync().get();
        Optional<Transaction> optionalTransaction = transaction.getTransaction();
        System.out.println(optionalTransaction);
        StringBuilder txInfo = new StringBuilder();
        if (optionalTransaction.isPresent()) {
            Transaction transactionInfo = optionalTransaction.get();
            Gson gson = new Gson();
            txInfo.append(gson.toJson(transactionInfo));
        }
        return txInfo.toString();
    }

    @GetMapping("/checkERC20")
    public void checkERC20Transfers(@RequestParam(value = "txHash") String txHash, HttpServletRequest request) throws Exception {

        Object idObject = request.getAttribute("id");
        if (idObject instanceof String) {
            blockChainInfoService.checkERC20Transfers(txHash, Integer.valueOf((String) idObject));
        }

    }
}